<template>
  <div class="musicListDetail" v-if="musicListDetail">
    <DetailInfo @handleSubClick='collectList' :isSub='isSub' :detailInfo='musicListDetail' />
    <!-- 歌曲列表 -->
    <div class="musicList">
      <el-tabs value="first" @tab-click="clickTab">
        <el-tab-pane label="歌曲列表" name="first">
          <!-- 表格 -->
          <music-table :songList='musicListDetail.tracks' :isMore='isMore' :listId='musicListDetail.id' @loadMore='loadMore' />
          <div class="loadMore" v-if="isMore && !this.$store.state.isLogin">
            登陆后查看更多音乐
          </div>
        </el-tab-pane>
        <el-tab-pane label="评论" name="second">
          <div class="commentList" v-if="comments.comments" v-loading="isCommentLoading">
            <!-- 精彩评论 -->
            <comment :commentType="'musicList'" :comments="comments.hotComments" :commentId="musicListDetail.id + ''" @getComment="getMusicListComment" @scrollToComment="scrollToComment" v-if="comments.hotComments" ref="hotComments">
              <div slot="title">精彩评论</div>
            </comment>
            <!-- 最新评论 -->
            <comment :comments="comments.comments" :commentType="'musicList'" :commentId="musicListDetail.id + ''" :isHotComment="comments.hotComments ? false : true" @getComment="getMusicListComment" @scrollToComment="scrollToComment" @transToHotComment="
                (info) =>
                  $refs.hotComments.floorComment(info.commentId, info.nickName)
              ">
              <div slot="title">热门评论</div>
            </comment>
          </div>
          <!-- 分页 -->
          <div class="page" v-show="comments.comments && comments.comments.length != 0">
            <el-pagination background layout="prev, pager, next" :total="comments.total" small :page-size="50" :current-page="currentCommentPage" @current-change="commentPageChange">
            </el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane label="收藏者" name="third">
          <user-list-card userType="musicListDetailPage" :userList="followedsListData.followedsList" :isLoad="followedsListData.isMore" @bottomLoad="bottomLoad"></user-list-card>
          <div class="tips" v-if="
              followedsListData.followedsList.length == 0 &&
              followedsListData.isLoaded == true
            ">
            暂无收藏者
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 返回顶部组件 -->
    <go-top scrollObj=".musicListDetail"></go-top>
  </div>
</template>

<script>
import MusicTable from 'components/musicTable/MusicTable.vue'
import { formatDate, handleNum, handleMusicTime } from 'plugins/utils'
import Comment from 'components/comment/Comment'
import GoTop from 'components/goTop/GoTop.vue'
import UserListCard from 'components/userListCard/UserListCard.vue'
import DetailInfo from './child/DetailInfo.vue'
export default {
  name: 'MusicListDetail',
  data() {
    return {
      musicListDetail: null,
      comments: {},
      // 当前评论页数
      currentCommentPage: 1,
      // 是否还有更多音乐
      isMore: false,
      // 用户是否收藏了当前歌单
      isSub: false,
      // 是否是用户创建的歌单
      isCreated: false,
      // 评论是否在加载
      isCommentLoading: false,
      // 是否禁止滚动加载
      scrollLoadDisabled: false,
      // 收藏者列表的变量
      followedsListData: {
        // 当前页数
        currentPage: 1,
        // 列表
        followedsList: [],
        // 是否还有更多
        isMore: false,
        // 是否已经加载过列表数据 （用于点击收藏者tab后第一次加载数据）
        isLoaded: false
      }
    }
  },
  components: {
    Comment,
    GoTop,
    UserListCard,
    MusicTable,
    DetailInfo
  },
  methods: {
    // 请求
    // 根据传来的 id 查询歌单
    async getMusicListDetail() {
      var timestamp = Date.parse(new Date())
      // console.log(this.$route.params.id);
      let result = await this.$request('/playlist/detail', {
        id: this.$route.params.id,
        timestamp
      })
      // console.log(result);

      let playlist = result.data.playlist
      playlist.trackCount = handleNum(playlist.trackCount)
      playlist.playCount = handleNum(playlist.playCount)
      playlist.createTime = formatDate(new Date(playlist.createTime), 'yyyy-MM-dd')
      // console.log(this.musicListDetail);
      // 判断是否还有更多音乐
      if (playlist.tracks.length != playlist.trackIds.length) {
        this.isMore = true
      }

      // 处理播放时间
      playlist.tracks = playlist.tracks.map((item, index) => {
        item.dt = handleMusicTime(item.dt)
        return item
      })

      this.musicListDetail = playlist
      // 判断用户是否喜欢该音乐
      // 直接两个循环性能损耗太厉害了 没什么思路暂时不做先
      // let likeMusicList = this.$store.state.likeMusicList;
    },
    // 获取歌单评论
    async getMusicListComment(type) {
      // 获取时间戳
      var timestamp = Date.parse(new Date())
      this.isCommentLoading = true

      if (type == 'changePage') {
        this.scrollToComment()
      }
      let res = await this.$request('/comment/playlist', {
        id: this.$route.params.id,
        offset: (this.currentCommentPage - 1) * 50,
        limit: 50,
        timestamp
      })
      console.log(res)
      if (res.data.code !== 200) {
        this.$message.error('获取评论失败,请稍后重试!')
      }
      this.comments = res.data
      this.isCommentLoading = false
      console.log('重新歌单获取评论')
    },

    scrollToComment() {
      let musicListDetail = document.querySelector('.musicListDetail')
      let listInfo = document.querySelector('.listInfo')
      // console.log("执行了这里 滚动到精彩评论", [listInfo]);
      musicListDetail.scrollTo({
        behavior: 'smooth',
        top: listInfo.clientHeight - 20
      })
    },

    // 获取歌曲详情
    async getMusicDetail(ids) {
      if (this.isMore == false) return
      this.scrollLoadDisabled = true

      let res = await this.$request('/song/detail', { ids })
      // 处理时间
      console.log(res)
      let songs = res.data.songs
      songs = songs.map((item, index) => {
        item.dt = handleMusicTime(item.dt)
        return item
      })
      this.musicListDetail.tracks = this.musicListDetail.tracks.concat(songs)
      // 判断是否还有更多音乐
      if (this.musicListDetail.tracks.length < this.musicListDetail.trackIds.length) {
        this.isMore = true
        this.scrollLoadDisabled = false
      } else {
        this.isMore = false
      }
    },

    // 请求用户歌单
    async getUserMusicList() {
      let timestamp = Date.parse(new Date())
      // 先从localStorage里面读取用户信息  如果登录成功是有存的
      this.userInfo = window.localStorage.getItem('userInfo') && JSON.parse(window.localStorage.getItem('userInfo'))
      let res = await this.$request('/user/playlist', {
        uid: this.userInfo.userId,
        timestamp
      })
      res = res.data.playlist
      let index = res.findIndex(item => item.subscribed == true)
      this.collectedMusicList = res.slice(index)
      // 将收藏的歌单上传至vuex
      this.$store.commit('updateCollectMusicList', this.collectedMusicList)
    },

    // 获取歌单收藏者
    async getMusicListFolloweds() {
      let res = await this.$request('/playlist/subscribers', {
        id: this.$route.params.id,
        offset: (this.followedsListData.currentPage - 1) * 20
      })
      this.followedsListData.isMore = res.data.more
      this.followedsListData.followedsList = this.followedsListData.followedsList.concat(res.data.subscribers)
    },

    // 评论点击翻页的回调
    commentPageChange(page) {
      this.currentCommentPage = page
      this.getMusicListComment('changePage')
    },

    // 点击el-tab-pane的回调
    clickTab(e) {
      console.log(e.index)
      if (e.index == 1 && !this.comments.comments) {
        this.getMusicListComment()
      } else if (e.index == 2 && !this.followedsListData.isLoaded) {
        this.getMusicListFolloweds()
        this.followedsListData.isLoaded = true
      }
    },
    // 点击加载所有音乐的回调
    loadMore() {
      if (!this.$store.state.isLogin) {
        this.$message.error('请先进行登录操作!')
        return
      }

      let arr = this.musicListDetail.trackIds.slice(this.musicListDetail.tracks.length)
      if (arr.length > 100) {
        arr = arr.slice(0, 100)
      }
      let ids = []
      ids = arr.map(v => v.id)
      this.getMusicDetail(ids.toString())
    },
    // 判断用户是否收藏了该歌单
    getIsSub() {
      this.isSub = this.$store.state.collectMusicList.some(item => item.id == this.$route.params.id)
    },
    // 判断是否是用户创建的歌单
    getIsCreated() {
      this.isCreated = this.$store.state.createdMusicList.some(item => item.id == this.$route.params.id)
    },
    // 点击收藏按钮的回调
    async collectList() {
      if (!this.$store.state.isLogin) {
        // this.$message.error("请先进行登录操作!");
        return
      }
      this.isSub = !this.isSub
      // 请求
      let timestamp = Date.parse(new Date())
      await this.$request('/playlist/subscribe', {
        id: this.$route.params.id,
        t: this.isSub ? 1 : 2,
        timestamp
      })
      // 请求收藏歌单列表并保存至vuex
      this.getUserMusicList()
    },

    // 收藏者列表触底的回调
    bottomLoad() {
      this.followedsListData.currentPage += 1
      this.getMusicListFolloweds()
    }
  },

  watch: {
    // 监听createdMusicList的变化
    '$store.state.createdMusicList'(current, last) {
      // 如果在收藏页面刷新，收藏歌单还没获取到，但是收藏按钮已经渲染了，所以在第一次获取到数据时，再渲染一次
      // 如果是刚刷新，last则为空
      if (last.length == 0) {
        this.getIsSub()
      }
    }
  },

  async mounted() {
    if (this.$store.state.isLogin) {
      // 先判断是否是用户创建的歌单
      this.getIsCreated()
      // 如果不是 再判断是否是收藏的歌单
      if (!this.isCreated) {
        this.getIsSub()
      }
    }
    await this.getMusicListDetail()
  }
}
</script>

<style scoped>
.musicListDetail {
  overflow-y: scroll;
}

.musicList {
  margin: -15px 15px 0;
}

.page {
  width: 100%;
  text-align: center;
  padding-bottom: 20px;
}

.placeholder {
  width: 100%;
  height: 50px;
}

.loadMore {
  width: 100%;
  height: 50px;
  font-size: 12px;
  color: #aaa;
  text-align: center;
  line-height: 50px;
  transform: scale(0.9);
}

.red {
  color: #ec4141;
}

.commentList /deep/ .el-loading-spinner {
  top: 40px;
}

.tips {
  font-size: 14px;
  margin: 30px 0;
  text-align: center;
}
</style>